package com.test.Util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库工具类
 * 提供数据库连接和基本操作功能
 */
public class DatabaseUtil {

    private static Properties properties;
    private static String url;
    private static String name;
    private static String password;
    private static String driver;
    private static String tableName;

    // 静态代码块，加载配置文件
    static {
        loadDatabaseConfig();
    }

    /**
     * 从配置文件加载数据库连接参数
     */
    private static void loadDatabaseConfig() {
        try {
            properties = new Properties();
            InputStream inputStream = DatabaseUtil.class.getClassLoader()
                    .getResourceAsStream("database.properties");

            if (inputStream == null) {
                throw new RuntimeException("无法找到database.properties配置文件");
            }

            properties.load(inputStream);
            inputStream.close();

            // 获取配置参数
            url = properties.getProperty("db.url");
            name = properties.getProperty("db.username");
            password = properties.getProperty("db.password");
            driver = properties.getProperty("db.driver");
            tableName = properties.getProperty("test.table.name");

        } catch (IOException e) {
            throw new RuntimeException("加载数据库配置文件失败", e);
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接对象
     */
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, name, password);
        } catch (ClassNotFoundException e) {
            throw new SQLException("数据库驱动未找到: " + e.getMessage(), e);
        }
    }

    /**
     * 关闭数据库连接
     * @param connection 数据库连接
     */
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.err.println("关闭数据库连接时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 关闭PreparedStatement
     * @param statement PreparedStatement对象
     */
    public static void closeStatement(PreparedStatement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                System.err.println("关闭PreparedStatement时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 关闭ResultSet
     * @param resultSet ResultSet对象
     */
    public static void closeResultSet(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                System.err.println("关闭ResultSet时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 关闭所有资源
     * @param connection 数据库连接
     * @param statement PreparedStatement
     * @param resultSet ResultSet
     */
    public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        closeResultSet(resultSet);
        closeStatement(statement);
        closeConnection(connection);
    }

    /**
     * 获取测试表名
     * @return 表名
     */
    public static String getTableName() {
        return tableName;
    }

    /**
     * 创建测试表
     * 如果表不存在则创建
     */
    public static void createTestTable() {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = getConnection();

            // 创建用户表的SQL
            String createTableSQL = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
                    "id INT AUTO_INCREMENT PRIMARY KEY, " +
                    "name VARCHAR(50) NOT NULL UNIQUE, " +
                    "email VARCHAR(100) NOT NULL, " +
                    "age INT " +
                    ")";

            statement = connection.prepareStatement(createTableSQL);
            statement.executeUpdate();

            System.out.println("✅ 测试表 " + tableName + " 创建成功！");

        } catch (SQLException e) {
            System.err.println("创建测试表失败: " + e.getMessage());
            throw new RuntimeException("创建测试表失败", e);
        } finally {
            closeAll(connection, statement, null);
        }
    }

    /**
     * 删除测试表
     * 用于测试完成后清理
     */
    public static void dropTestTable() {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = getConnection();

            String dropTableSQL = "DROP TABLE IF EXISTS " + tableName;
            statement = connection.prepareStatement(dropTableSQL);
            statement.executeUpdate();

            System.out.println("✅ 测试表 " + tableName + " 删除成功！");

        } catch (SQLException e) {
            System.err.println("删除测试表失败: " + e.getMessage());
        } finally {
            closeAll(connection, statement, null);
        }
    }

    /**
     * 清空测试表数据
     */
    public static void truncateTestTable() {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = getConnection();

            String truncateSQL = "TRUNCATE TABLE " + tableName;
            statement = connection.prepareStatement(truncateSQL);
            statement.executeUpdate();

            System.out.println("✅ 测试表 " + tableName + " 数据清空成功！");

        } catch (SQLException e) {
            System.err.println("清空测试表数据失败: " + e.getMessage());
        } finally {
            closeAll(connection, statement, null);
        }
    }
}

